//
//  AddAddressViewController.m
//  YunGou
//
//  Created by macbook on 16/5/18.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "AddAddressViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "YGPickView.h"
#import "NSString+Regexp.h"

@interface AddAddressViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *receiver;
@property (weak, nonatomic) IBOutlet UITextField *mobile;
@property (weak, nonatomic) IBOutlet UILabel *area;
@property (weak, nonatomic) IBOutlet UITextField *detailAddress;
@property (weak, nonatomic) IBOutlet UITextField *code;
@property (weak, nonatomic) IBOutlet UISwitch *isDefault;

@property (nonatomic,strong) YGPickView *pickView;
@property (nonatomic,strong) UIPickerView *areaPicker;
@property (nonatomic,strong) UIView *bgView;

@property (nonatomic,strong) NSArray *provinceArr;
@property (nonatomic,strong) NSArray *cityArr;
@property (nonatomic,strong) NSArray *districtArr;
@property (nonatomic,assign) NSInteger provinceIndex;
@property (nonatomic,assign) NSInteger cityIndex;
@property (nonatomic,assign) NSInteger districtIndex;
@property (nonatomic,copy) NSString *allName;
@end

@implementation AddAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _isDefault.on = NO;
    _isDefault.onTintColor = ThemeColor;
    
    UIBarButtonItem *rightBarItem = [UIBarButtonItem barButtonTitle:@"保存" image:nil frame:CGRectMake(0, 0, 44, 44) target:self sel:@selector(saveClick)];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    [self loadArea];
    
    if ([self.title isEqualToString:@"编辑地址"]) {
        _receiver.text = _receiveAddressModel.shouhuoren;
        _mobile.text = _receiveAddressModel.mobile;
        _area.text = _receiveAddressModel.sheng;
        _detailAddress.text = _receiveAddressModel.jiedao;
        if ([_receiveAddressModel.isDefault isEqualToString:@"Y"]) {
            _isDefault.on = YES;
        }else{
            _isDefault.on = NO;
        }
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealKeyboardShow) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealKeyboardHide) name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealKeyboardShow{
    [self.view addSubview:self.bgView];
}

- (void)dealKeyboardHide{
    [self.bgView removeFromSuperview];
    self.bgView = nil;
    [self.view endEditing:NO];
}


//加载地址
- (void)loadArea{
    NSString *provincePath = [[NSBundle mainBundle] pathForResource:@"province" ofType:@"json"];
    NSData *provinceData = [NSData dataWithContentsOfFile:provincePath];
    NSDictionary *provinceDic = [NSJSONSerialization JSONObjectWithData:provinceData options:kNilOptions error:nil];
    _provinceArr = [provinceDic objectForKey:@"province"];
    
    id cityItem = [_provinceArr objectAtIndex:0];
    NSString *cityFilePath = [[NSBundle mainBundle] pathForResource:[cityItem objectForKey:@"spellName"] ofType:@"json"];
    NSData *cityData = [NSData dataWithContentsOfFile:cityFilePath];
    NSDictionary *cityDic = [NSJSONSerialization JSONObjectWithData:cityData options:kNilOptions error:nil];
    _cityArr = [cityDic objectForKey:@"city"];
    
    id districtItem = [_cityArr objectAtIndex:0];
    NSString *districtFilePath = [[NSBundle mainBundle] pathForResource:[districtItem objectForKey:@"spellName"] ofType:@"json"];
    NSData *districtData = [NSData dataWithContentsOfFile:districtFilePath];
    NSDictionary *districtDic = [NSJSONSerialization JSONObjectWithData:districtData options:kNilOptions error:nil];
    _districtArr = [districtDic objectForKey:@"district"];
    _allName = [NSString stringWithFormat:@"%@%@%@", [[_provinceArr objectAtIndex:0] objectForKey:@"name"], [[_cityArr objectAtIndex:0] objectForKey:@"name"], [[_districtArr objectAtIndex:0] objectForKey:@"name"]];
}

- (void)saveClick{
    NSString *receiver = _receiver.text;
    NSString *mobile = _mobile.text;
    NSString *area = _area.text;
    NSString *detailAddress = _detailAddress.text;
    NSString *code = _code.text;
    NSString *isDefault = _isDefault.isOn?@"Y":@"N";
    if (receiver.length == 0) {
        [MBProgressHUD showError:@"请输入收货人姓名"];
    }else if (mobile.length == 0){
        [MBProgressHUD showError:@"请输入电话号码"];
    }else if (![NSString isMobileNumber:mobile]){
        [MBProgressHUD showError:@"手机号码格式不正确"];
    }else if (area.length == 0){
        [MBProgressHUD showError:@"请选择区域"];
    }else if (detailAddress.length == 0){
        [MBProgressHUD showError:@"请输入详细地址"];
    }else{
        if ([self.title isEqualToString:@"编辑地址"]) {
            [NetWorkTool editReceiveAddressWithId:_receiveAddressModel.Id houHuoren:receiver mobile:mobile address:area jieDao:detailAddress code:code isDefault:isDefault success:^(id object) {
                if ([object[@"code"] integerValue] == 1) {
                    [MBProgressHUD showSuccess:@"地址编辑成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
            } failure:^(NSError *error) {
                
            }];
        }else{
            [NetWorkTool addReceiveAddressWithShouHuoren:receiver mobile:mobile address:area jieDao:detailAddress code:code isDefault:isDefault success:^(id object) {
                if ([object[@"code"] integerValue] == 1) {
                    [MBProgressHUD showSuccess:@"地址添加成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
            } failure:^(NSError *error) {
                
            }];

        }
    }
}

#pragma -mark tableViewDelegate and DataSource

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 2) {
        self.areaPicker.frame = CGRectMake(0, 0, ScreenWidth - 12, 246);
        [self.pickView.bottomView addSubview:self.areaPicker];
        
        FZLog(@"%f--%@----%@",ScreenWidth,NSStringFromCGRect(self.areaPicker.frame),NSStringFromCGRect(self.pickView.bottomView.bounds));
    }
}

#pragma -mark pickViewDelegate
#pragma -mark pickViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSInteger row = 0;
    switch (component)
    {
        case 0:
            row = [_provinceArr count];
            break;
        case 1:
            row = [_cityArr count];
            break;
        case 2:
            row = [_districtArr count];
            break;
        default:
            break;
    }
    return row;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *title = @"";
    id item;
    switch (component)
    {
        case 0:
            item = [_provinceArr objectAtIndex:row];
            _provinceIndex = row;
            break;
        case 1:
            item = [_cityArr objectAtIndex:row];
            _cityIndex = row;
            break;
        case 2:
            item = [_districtArr objectAtIndex:row];
            _districtIndex = row;
            break;
        default:
            break;
    }
    if (item)
    {
        title = [item objectForKey:@"name"];
    }
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (0 == component)
    {
        id cityItem = [_provinceArr objectAtIndex:row];
        NSString *cityFilePath = [[NSBundle mainBundle] pathForResource:[cityItem objectForKey:@"spellName"] ofType:@"json"];
        if (cityFilePath)
        {
            NSData *cityData = [NSData dataWithContentsOfFile:cityFilePath];
            NSDictionary *cityDic = [NSJSONSerialization JSONObjectWithData:cityData options:kNilOptions error:nil];
            _cityArr = [cityDic objectForKey:@"city"];
            
            id districtItem = [_cityArr objectAtIndex:0];
            NSString *districtFilePath = [[NSBundle mainBundle] pathForResource:[districtItem objectForKey:@"spellName"] ofType:@"json"];
            if (districtFilePath)
            {
                NSData *districtData = [NSData dataWithContentsOfFile:districtFilePath];
                NSDictionary *districtDic = [NSJSONSerialization JSONObjectWithData:districtData options:kNilOptions error:nil];
                _districtArr = [districtDic objectForKey:@"district"];
            } else {
                _districtArr = [[NSArray alloc] init];
            }
        } else {
            _cityArr = [[NSArray alloc] init];
            _districtArr = [[NSArray alloc] init];
        }
        
        [pickerView reloadComponent:1];
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:1 animated:NO];
        [pickerView selectRow:0 inComponent:2 animated:NO];
        
        _allName = [NSString stringWithFormat:@"%@%@%@", [[_provinceArr objectAtIndex:row] objectForKey:@"name"], [[_cityArr objectAtIndex:0] objectForKey:@"name"], [[_districtArr objectAtIndex:0] objectForKey:@"name"]];
    }
    
    if (1 == component)
    {
        id districtItem = [_cityArr objectAtIndex:row];
        NSString *districtFilePath = [[NSBundle mainBundle] pathForResource:[districtItem objectForKey:@"spellName"] ofType:@"json"];
        if (districtFilePath)
        {
            NSData *districtData = [NSData dataWithContentsOfFile:districtFilePath];
            NSDictionary *districtDic = [NSJSONSerialization JSONObjectWithData:districtData options:kNilOptions error:nil];
            _districtArr = [districtDic objectForKey:@"district"];
        } else {
            _districtArr = [[NSArray alloc] init];
        }
        
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:2 animated:NO];
        
        _allName = [NSString stringWithFormat:@"%@%@%@", [[_provinceArr objectAtIndex:_provinceIndex] objectForKey:@"name"], [[_cityArr objectAtIndex:row] objectForKey:@"name"], [[_districtArr objectAtIndex:0] objectForKey:@"name"]];
    }
    
    if (2 == component) {
        _allName = [NSString stringWithFormat:@"%@%@%@", [[_provinceArr objectAtIndex:_provinceIndex] objectForKey:@"name"], [[_cityArr objectAtIndex:_cityIndex] objectForKey:@"name"], [[_districtArr objectAtIndex:row] objectForKey:@"name"]];
    }
}

#pragma -mark 懒加载相关
- (YGPickView *)pickView{
    if (!_pickView) {
        _pickView = [YGPickView nibInitializtion];
        _pickView.userInteractionEnabled = YES;
        _pickView.frame = CGRectMake(0,ScreenHeight - 305 - 49, ScreenWidth, 305);
        __weak typeof(self) ws = self;
        _pickView.pickerViewBlock = ^(NSInteger tag){
            if (tag == 2) {
                ws.area.text = ws.allName;
            }
                [ws.pickView removeFromSuperview];
                ws.pickView = nil;
        };
        [self.tableView addSubview:_pickView];
    }
    return _pickView;
}

- (UIPickerView *)areaPicker{
    if (!_areaPicker) {
        _areaPicker = [[UIPickerView alloc] init];
        _areaPicker.delegate = self;
        _areaPicker.dataSource = self;
    }
    return _areaPicker;
}

- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:self.view.bounds];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyBoard)];
        [_bgView addGestureRecognizer:tap];
    }
    return _bgView;
}

- (void)hiddenKeyBoard{
    [self.view endEditing:YES];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
